//
//  ByMenuView.m
//  hutouben_ios
//
//  Created by justiOS on 16/12/1.
//  Copyright © 2016年 mc. All rights reserved.
//

#import "ByMenuView.h"

@implementation ByMenuView
{
    NSInteger _prevTag;
    UIView *_selectView;
}
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = HTB_BG_GRAY;
        self.layer.cornerRadius = 5;
        self.layer.masksToBounds = YES;
    }
    
    return self;
}

- (void)setTitleAry:(NSArray *)titleAry {
    _titleAry = titleAry;
    [self _initViews];
}

#pragma mark -- 创建视图 --
- (void)_initViews {
    
    NSArray *titles = _titleAry;
    CGFloat width = self.width / titles.count;
    CGFloat height = self.height;
    CGFloat x, y = 0;
    for (int i = 0; i < titles.count; i ++) {
        
        x = i * width;
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(x, y, width, height);
        button.layer.cornerRadius = 5;
        button.layer.masksToBounds = YES;
        button.backgroundColor = [UIColor clearColor];
        [button setTitle:titles[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [button setTitleColor:HTB_TEXT_COLOR2 forState:UIControlStateNormal];
        button.titleLabel.font = FONT(18);
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        button.tag = 10 + i;
        
        if (button.tag == 10) {
            _prevTag = button.tag;
            self.seletedButton = button;
            button.selected = YES;
            button.backgroundColor = HTB_THEME_COLOR;
        }
    }
}


#pragma mark - 点击事件
- (void)buttonAction:(UIButton *)button {
    
    // 点击了已经选中的按钮
    if (button.tag == _prevTag) {
        return;
    }
    button.selected = !button.selected;
    // 更改上个被选中的索引
    _prevTag = button.tag;
    self.seletedButton.backgroundColor = [UIColor clearColor];
    self.seletedButton.selected = NO;
    
    self.seletedButton = button;
    button.backgroundColor = HTB_THEME_COLOR;
    

    
    // 触发代理点击事件
    if (self.chooseBlock) {
        self.chooseBlock(_prevTag - 10);
    }
}

@end
